package com.itheima.dao;

import com.github.pagehelper.Page;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

/**
 * 用户 持久层接口
 */
public interface UserDao {

    /**
     * 根据用户名查询用户
     *
     * @param username 用户名
     * @return 用户
     */
    @Select("select * from  t_user where username=#{username} ")
    User findByUsername(String username);

    /**
     * 分页查询
     * 根据条件查询用户
     *
     * @param queryString 查询条件
     * @return 用户集合
     *
     * <script>select * from t_checkitem <if test="queryString!=null and queryString!=''">where code like "%"#{queryString}"%" or name like "%"#{queryString}"%"  </if></script>
     */
    @Select("<script> select * from t_user <if test=\"queryString !=null and queryString !=''\"> where username like \"%\"#{queryString}\"%\" </if></script>")
    Page<User> selectByCondition(@Param("queryString") String queryString);

    /**
     * 添加用户  查询用户的主键
     *
     * @param user 用户
     */
    @Insert("insert into t_user (birthday,gender,username,password,remark,station,telephone) values(#{birthday},#{gender},#{username},#{password},#{remark},#{station},#{telephone})")
    @SelectKey(statement = "select last_insert_id()", before = false, keyProperty = "id", keyColumn = "id", resultType = Integer.class)
    void add(User user);

    /**
     * 添加用哪个户-角色中间表
     *
     * @param map 用户id  角色id
     */
    @Insert("insert into t_user_role values(#{userId},#{roleId})")
    void setUserIdAndRoleId(Map<String, Integer> map);

    /**
     * 根据id查询用户
     *
     * @param id 用户id
     * @return 用户
     */
    @Select("select * from t_user where id=#{id}")
    User findById(Integer id);

    /**
     * 根据用户id,查询用户具有所有权限的id
     *
     * @param userId 用户id
     * @return 权限的id集合
     */
    @Select("select role_id from t_user_role where user_id=#{userId} ")
    List<Integer> findRoleIdsByUserId(Integer userId);

    /**
     * 根据用户id删除用户-角色中间表
     *
     * @param userId  角色id
     */
    @Delete("delete from t_user_role where user_id=#{userId} ")
    void deleteAssociation(Integer userId);

    /**
     * 编辑用户
     *
     * @param user 用户
     */
    @Update("update t_user set birthday=#{birthday},gender=#{gender},username=#{username},password=#{password},remark=#{remark},station=#{station},telephone=#{telephone} where id=#{id} ")
    void edit(User user);

    /**
     * 根据id删除用户
     *
     * @param id 用户id
     */
    @Delete("delete  from t_user where id=#{id}")
    void delete(Integer id);

}
